# strategy_instance.py
import time
from typing import Dict, Any

class StrategyInstance:
    def __init__(self, stock_code: str, params: Dict[str, Any]):
        self.stock_code = stock_code
        self.params = params.copy()  # 避免外部修改影响
        self.is_ordering = False
        self.pending_order_id = None
        self.last_signal_time = 0.0
        self.created_at = time.time()

    def check_signal(self, tick) -> bool:
        """
        【你的策略逻辑】
        示例:价格突破20日均线且成交量放大
        """
        # 示例参数：params = {"ma_window": 20, "vol_multiplier": 1.5}
        ma_window = self.params.get("ma_window", 20)
        vol_mult = self.params.get("vol_multiplier", 1.5)

        # 注意：QMT tick 对象字段示例
        price = tick.last_price
        volume = tick.volume
        # 这里应从缓存获取历史数据计算 MA，此处简化
        # 实际中建议用 context.data 缓存或 TA-Lib

        # 简化信号：当前价 > 20 且成交量 > 1000
        if price > 20 and volume > 1000:
            # 冷却时间：防止高频触发（例如 5 秒内只触发一次）
            if time.time() - self.last_signal_time > self.params.get("cool_down", 5):
                self.last_signal_time = time.time()
                return True
        return False

    def on_tick(self, tick, account_id: str):
        """在 QMT 主线程中调用"""
        if self.is_ordering:
            return  # 等待上一笔成交完成

        if self.check_signal(tick):
            try:
                from qmt import order_stock
                order_id = order_stock(
                    account_id=account_id,
                    stock_code=self.stock_code,
                    volume=self.params.get("order_volume", 100),
                    side='buy',
                    order_type='limit',
                    price=tick.last_price
                )
                self.is_ordering = True
                self.pending_order_id = order_id
                print(f"[{self.stock_code}] 下单成功，订单ID: {order_id}")
            except Exception as e:
                print(f"[{self.stock_code}] 下单失败: {e}")

    def on_order_status(self, order):
        """处理成交回报"""
        if self.pending_order_id and order.order_id == self.pending_order_id:
            if order.status in ["FILLED", "CANCELED", "REJECTED", "PARTTRADED"]:
                print(f"[{self.stock_code}] 订单状态更新: {order.status}")
                self.is_ordering = False
                self.pending_order_id = None

    def update_params(self, new_params: Dict[str, Any]):
        """热更新参数"""
        self.params.update(new_params)
        print(f"[{self.stock_code}] 参数已更新: {new_params}")

    def to_dict(self):
        """用于 API 返回状态"""
        return {
            "stock_code": self.stock_code,
            "is_ordering": self.is_ordering,
            "pending_order_id": self.pending_order_id,
            "params": self.params,
            "created_at": self.created_at
        }